<template>
  <!-- 数据责任列表 -->
  <div>
    <div style="display: flex; justify-content: flex-end">
      <el-select
        v-model="value"
        placeholder="请选择审批状态"
        @change="changeSelect"
      >
        <el-option
          v-for="item in options1"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-select
        v-model="value1"
        placeholder="请选择数据责任状态"
        @change="changeSelect1"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-input
        placeholder="请输入需求资源名称"
        v-model="name"
        class="input-with-select"
        style="width: 300px"
        clearable
      >
        <el-button
          slot="append"
          icon="el-icon-search"
          @click="searchBtn"
        ></el-button>
      </el-input>
    </div>

    <el-table
      :data="tableData"
      border
      style="width: 100%; margin: 10px 0"
      height="560"
    >
      <el-table-column
        fixed
        prop="taskName"
        label="数据责任名称"
        width="200"
        align="center"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column
        prop="taskDept"
        label="责任部门"
        width="120"
        align="center"
        :show-overflow-tooltip="true"
      >
      </el-table-column>
      <el-table-column
        prop="taskUser"
        label="责任人"
        width="120"
        align="center"
      >
      </el-table-column>
      <el-table-column
        prop="taskDescri"
        label="责任描述"
        align="center"
        width="200"
      >
      </el-table-column>
      <el-table-column
        prop="taskStatus"
        label="责任状态"
        width="120"
        align="center"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.taskStatus === 0">待处理</span>
          <span v-else-if="scope.row.taskStatus === 1">处理中 </span>
          <span v-else-if="scope.row.taskStatus === 2">已完成</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="spzt"
        label="撤销审批状态"
        width="120"
        align="center"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.spzt === '0'">待审核</span>
          <span v-else-if="scope.row.spzt === '1'">通过 </span>
          <span v-else-if="scope.row.spzt === '2'">退回</span>
          <span v-else>未申请</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="taskType"
        label="责任类型"
        width="120"
        align="center"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.taskType === 0">数据库</span>
          <span v-else-if="scope.row.taskType === 1">api接口 </span>
          <span v-else-if="scope.row.taskType === 2">文件</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="auditTime"
        label="创建时间"
        width="200"
        align="center"
      >
        <template slot-scope="scope" v-if="scope.row.createTime && scope.row.createTime !== null">
          {{ scope.row.createTime | formatDate }}
        </template>
      </el-table-column>
      <el-table-column
        fixed="right"
        align="center"
        label="操作"
        width="120">
        <template slot-scope="scope">
          <el-button @click="handleClickDetail(scope.row)" type="text" size="small">查看</el-button>
<!--          <el-button type="text" size="small" @click="cxBtn(scope.row)"  v-if="scope.row.spzt != '0' && scope.row.spzt != '1' && scope.row.spzt != '2'">撤销</el-button>-->
          <el-button type="text" size="small" @click="spBtn(scope.row)" v-if="scope.row.spzt === '0'">审批</el-button>
<!--          <el-button type="text" size="small" @click="scBtn(scope.row)"  v-if="scope.row.spzt === '1'">删除</el-button>-->
<!--          <el-button type="text" size="small" @click="cxtjBtn(scope.row)"  v-if="scope.row.spzt === '2'">重新提交</el-button>-->
        </template>
      </el-table-column>
    </el-table>
    <div style="display: flex; justify-content: flex-end">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="prev, pager, next, sizes, jumper"
        :total="totalNum"
      >
      </el-pagination>
    </div>
    <!--        详情弹窗-->
    <el-dialog
      :visible.sync="dialogVisible"
      width="80%"
    >
      <el-descriptions title="申请详情">
        <el-descriptions-item label="数据责任名称">{{detailList.taskName}}</el-descriptions-item>
        <el-descriptions-item label="数据责任类型">
          {{detailList.taskType === 0
          ? '数据库'
          : detailList.taskType === 1
            ? 'API 接口'
            : detailList.taskType === 2
              ? '文件'
              : '未知类型'}}
        </el-descriptions-item>
        <el-descriptions-item label="数据责任描述">{{ detailList.taskDescri }}</el-descriptions-item>
        <el-descriptions-item label="数据责任状态">
          {{detailList.taskStatus === 0
          ? '待处理'
          : detailList.taskStatus === 1
            ? '处理中'
            : detailList.taskStatus === 2
              ? '已完成'
              : '未知类型'}}
        </el-descriptions-item>
        <el-descriptions-item label="撤销审批编号">{{detailList.spbh}}</el-descriptions-item>
        <el-descriptions-item label="数据责任撤销审批状态">
          {{detailList.spzt === '0'
          ? '待审核'
          : detailList.spzt === '1'
            ? '通过'
            : detailList.spzt === '2'
              ? '退回'
              : '未知类型'}}
        </el-descriptions-item>
        <el-descriptions-item label="数据责任撤销审批意见">{{detailList.spyj}}</el-descriptions-item>
        <el-descriptions-item label="撤销审批时间">{{detailList.spsj}}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{detailList.createTime | formatDate}}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{detailList.updateTime | formatDate}}</el-descriptions-item>
        <el-descriptions-item label="更新人">{{detailList.updateBy}}</el-descriptions-item>
        <el-descriptions-item label="文件 ">
          <span style="color: #0f52b6;cursor: pointer" @click="xzBtn(detailList.file)">
             {{ detailList.file ? detailList.file.fileName : '无' }}
          </span>
        </el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
  </span>
    </el-dialog>
    <!--    修改弹窗-->
    <el-dialog title="审批" :visible.sync="dialogFormVisibleXg">
      <el-form :model="ruleFormXg" :rules="rulesXg" ref="ruleFormXg" label-width="100px" class="demo-ruleForm">
        <el-form-item label="审批结果" prop="spzt">
          <el-radio
            v-for="(item, index) in tabsList"
            :key="index"
            v-model="ruleFormXg.spzt"
            :label="index"
            style="margin-top: 10px"
          >{{ item }}</el-radio
          >
        </el-form-item>
        <el-form-item label="责任意见" prop="spyj">
          <el-input
            type="textarea"
            placeholder="请输入内容"
            v-model="ruleFormXg.spyj"
            maxlength="30"
            show-word-limit
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitFormXg('ruleFormXg')">确定</el-button>
          <el-button @click="resetFormXg('ruleFormXg')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!--    撤销弹窗-->
<!--    <el-dialog title="撤销" :visible.sync="dialogFormVisibleCx">-->
<!--      <el-form :model="ruleFormCx" :rules="rulesCx" ref="ruleFormCx" label-width="100px" class="demo-ruleForm">-->
<!--        <el-form-item label="审批人" prop="spr">-->
<!--          <el-select v-model="ruleFormCx.spr" placeholder="请选择撤销审批人">-->
<!--            <el-option-->
<!--              v-for="item in cxsprlist"-->
<!--              :key="item.value"-->
<!--              :label="item.label"-->
<!--              :value="item.value">-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="撤销理由" prop="deleteReason">-->
<!--          <el-input-->
<!--            type="textarea"-->
<!--            placeholder="请输入内容撤销理由"-->
<!--            v-model="ruleFormCx.deleteReason"-->
<!--            maxlength="30"-->
<!--            show-word-limit-->
<!--          >-->
<!--          </el-input>-->
<!--        </el-form-item>-->

<!--        <el-form-item label="上传文件">-->
<!--          <el-upload-->
<!--            class="upload-demo"-->
<!--            :action="xhDomain + `/api/datatask/upload/${sxid}`"-->
<!--            :on-preview="handlePreview"-->
<!--            :headers="headers"-->
<!--            :on-remove="handleRemove"-->
<!--            :on-success="handleSuccess"-->
<!--            :before-remove="beforeRemove"-->
<!--            :limit="1"-->
<!--            :on-exceed="handleExceed"-->
<!--            :file-list="fileList"-->
<!--            :show-file-list="false"-->
<!--            :before-upload="beforeUpload"-->
<!--            :on-progress="handleProgress"-->
<!--            :on-error="handleError"-->
<!--          >-->
<!--            <el-button size="small" type="primary">点击上传</el-button>-->
<!--            &lt;!&ndash; <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> &ndash;&gt;-->
<!--          </el-upload>-->
<!--        </el-form-item>-->
<!--        <el-form-item>-->
<!--          <el-button type="primary" @click="submitFormCx('ruleFormCx')">确定</el-button>-->
<!--          <el-button @click="resetFormCx('ruleFormCx')">重置</el-button>-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--    </el-dialog>-->
  </div>
</template>
<script>
import {
  getbbmsjzr,
  cxDeletebyid,
  getspr,
  gecxtj,
  getbbmsjzrDetail,
  getComplete,
  getuserbydept,
  getuserSpr,
  getuserDelete,
  getDeletebyid,
  getGetbyspr
} from "@/utils/httpUtils";
export default {
  data() {
    return {
      tabsList: ["通过", "退回"],
      sxid:'',
      xhDomain:xhDomain,
      fileList: [],
      headers: { Authorization: localStorage.getItem('token') },
      cxsprlist:[],
      dialogFormVisibleCx:false,
      ruleFormCx:{
        spr:'',
        deleteReason:'',
        id:''
      },
      rulesCx:{
        spr:[
          { required: true, message: '请选择审批人', trigger: 'change' }
        ],
        deleteReason:[
          { required: true, message: '请输入内容撤销理由', trigger: 'blur' }
        ]
      },
      zrrlist:[],
      ruleFormXg: {
        spzt: '',
        spyj:'',
        id:''
      },
      rulesXg: {
        spzt: [
          { required: true, message: '请选择审批状态', trigger: 'change' },
        ],
        spyj:[
          { required: true, message: '请输入责任描述', trigger: 'blur' }
        ]
      },
      dialogFormVisibleXg:false,
      sprlist:[],
      dialogVisible: false,
      show: false,
      value: "",
      value1: "",
      options: [
        {
          value: "0",
          label: "待处理",
        },
        {
          value: "1",
          label: "处理中",
        },
        {
          value: "2",
          label: "已完成",
        },
      ],
      options1: [
        {
          value: "0",
          label: "待审批",
        },
        {
          value: "1",
          label: "通过",
        },
        {
          value: "2",
          label: "退回",
        },
      ],
      name: "",
      tableData: [],
      activeName: "dataResource",
      currentPage: 1,
      pageNo: 1,
      pageSize: 10,
      status: "",
      status1:'',
      totalNum: 0,
      detailList:{}
    };
  },
  mounted() {
    this.initData()
    // this.getsprFn()
  },
  //   处理1703592547000 时间格式
  filters: {
    formatDate(timestamp) {
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
  },
  methods: {
    xzBtn(file){
      console.log(file,"file")
      //   文件下载
      this.$axios({
        url: xhDomain + `/api/interact/download/${file.fileId}`,
        method: 'post',
        responseType: 'blob', // 确保响应是二进制数据
        headers: {
          'Content-Type': 'application/json',
          "Authorization": JSON.parse(localStorage.getItem('token'))
        },
      }).then((res) => {
        console.log(res, 'res')
        const blob = new Blob([res.data], { type: 'application/octet-stream' });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = file.fileName; // 设置下载文件的文件名，可以根据需要修改
        document.body.appendChild(a);
        a.click();
        setTimeout(() => {
          document.body.removeChild(a);
          window.URL.revokeObjectURL(url);
        }, 100);
      }).catch((err) => {
        console.log(err,"err")
        // responseType: 'blob' 这个类型获取报错提示
        if (err.response.data.type === 'application/json') {
          const fileReader = new FileReader();
          fileReader.readAsText(err.response.data, 'utf-8');
          fileReader.onload = function () {
            const result = JSON.parse(fileReader.result);
            console.log(result, 'result');
            this.$message.error(result.message);
          }.bind(this); // Bind `this` to the onload function
          return;
        }

        const content = err.data
        const blob = new Blob([content], {
          type: "application/octet-stream"
        }) //构造一个blob对象来处理数据
        // this.$message.error(err.response.message)
      })
    },
    spBtn(row){
      this.dialogFormVisibleXg = true
      this.ruleFormXg.id = row.id
    },
    cxtjBtn(row){

    },
    scBtn(row){
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        getDeletebyid({id:row.id}).then(res=>{
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.initData()
        }).catch((err)=>{
          console.log(err,"err")
          this.$message({
            type: 'error',
            message: err.response.data.message
          });
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        });
      })
    },
    handleProgress(event, file, fileList) {
      // this.progress = Math.round(event.percent); // 更新进度条
    },
    beforeUpload(file) {
      // this.uploading = true; // 开始上传时显示进度条
      // this.progress = 0; // 重置进度条
      // this.uploadStatus = ''; // 重置上传状态
    },
    handleError(err, file, fileList) {
      console.error('Upload error:', err, file, fileList);
      // this.uploading = false; // 隐藏进度条
      // this.progress = 0; // 重置进度条
      // this.uploadStatus = 'exception'; // 设置上传状态为异常
      this.$message.error('上传失败，请重试'); // 显示错误提示信息
    },
    handlePreview(file) {
      console.log(file);
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handleSuccess() {
      console.log('上传成功');
      // 清空文件列表并重置上传组件
      // this.uploading = false; // 隐藏进度条
      // this.progress = 0; // 重置进度条
      // this.uploadStatus = 'success'; // 设置上传状态为成功
      // this.fileList = []; // 清空文件列表
      // this.getFileData();
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`最多只能上传 ${this.limit} 个文件`);
      this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    cxsprlistFn(){
      getuserSpr().then(res=>{
        console.log(res,'撤销审批人')
        this.cxsprlist = res.map(item => ({
          value: item.nickName,
          label: item.nickName
        }));
      })
    },
    submitFormCx(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          getuserDelete(this.ruleFormCx).then(res=>{
            console.log(res,"撤销")
            this.$message({
              message: res.msg,
              type: 'success'
            });
            this.initData()
            this.dialogFormVisibleCx = false
            this.resetFormCx('ruleFormCx')
          })
        } else {
          console.log('error submit!!');
          return false;
        }

      });
    },
    resetFormCx(formName){
      this.$refs[formName].resetFields();
    },
    getuserbydeptFn(){
      getuserbydept().then(res=>{
        console.log(res,'获取责任人')
        this.zrrlist = res.map(item => ({
          value: item,
          label: item
        }));
      })
    },
    submitFormXg(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert('submit!');
          getComplete(this.ruleFormXg).then(res=>{
            console.log(res,"1123")
            this.$message({
              message: res.msg,
              type: 'success'
            });
            this.dialogFormVisibleXg = false
            this.resetFormXg('ruleFormXg')
            this.initData()
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetFormXg(formName) {
      this.$refs[formName].resetFields();
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    cxspBtn(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const formattedRuleForm = {
            ...this.ruleForm,
            dataDept:this.selectedLabel,
            appDept:this.selectedLabelSq,
          };
          getupdatas(formattedRuleForm).then(res=>{
            console.log(res,"重新提交修改")
            this.$message({
              message: res,
              type: "success",
            });
            this.dialogFormVisibleCxtj = false
          })
        }else {
          console.log("error submit!!");
          return false;
        }
      })
    },
    // getsprFn(){
    //   getspr().then(res=>{
    //     console.log(res,"审批人")
    //     this.sprlist = res.map(item => ({
    //       value: item.nickName,
    //       label: item.nickName
    //     }));
    //   })
    // },


    xgBtn(row){
      this.dialogFormVisibleXg = true
      getbbmsjzrDetail({id:row.id}).then(res=>{
        console.log(res,'回显')
        this.ruleFormXg = res
        this.ruleFormXg.taskStatus = String(res.taskStatus)

      })
      this.getuserbydeptFn()
    },
    cxBtn(row){
      this.dialogFormVisibleCx = true
      this.cxsprlistFn()
      this.sxid = row.id
      this.ruleFormCx.id = row.id
      // this.$confirm('是否撤回?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // }).then(() => {
      //   cxDeletebyid({id:row.id}).then(res=>{
      //     console.log(res,"撤销123")
      //     if(res.code == 200){
      //       this.$message({
      //         type: 'success',
      //         message: '撤回成功!'
      //       });
      //       this.initData()
      //     }
      //   }).catch((err)=>{
      //     console.log(err,"err")
      //     this.$message({
      //       type: 'error',
      //       message: err.response.data.message
      //     });
      //   })
      // }).catch(() => {
      //   this.$message({
      //     type: 'info',
      //     message: '已取消'
      //   });
      // })

    },
    handleClickDetail(row){
      console.log(row.id, "row")
      getbbmsjzrDetail({id:row.id}).then(res=>{
        console.log(res,'详情')
        this.dialogVisible = true
        this.detailList = res
      })
    },
    searchBtn() {
      this.initData();
    },

    changeSelect(val) {
      console.log(val, "val");
      this.status = val;
      this.initData();
    },
    changeSelect1(val) {
      console.log(val, "val");
      this.status1 = val;
      this.initData();
    },
    // 初始化数据
    initData() {
      getGetbyspr({
        pageNum: this.pageNo,
        pageSize: this.pageSize,
        taskName: this.name,
        taskStatus:this.value,
        spzt:this.value1
      }).then((res) => {
        console.log(res, "我的申请，数据资源");
        this.tableData = res.content;
        this.totalNum = res.totalElements;
        this.name = "";
      });
    },

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.initData();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNo = val;
      this.initData();
    },
  },
};
</script>
<style  scoped>
.listToggle {
  padding: 13px 20px;
}

.listToggle.backBtn {
  border-bottom: 4px solid #198ef8;
}
</style>



